import React, {useCallback, useReducer} from 'react';

const initialState = {number: 0};
// const INCREMENT = 'INCREMENT';
// const DECREMENT = 'DECREMENT';
//
// function reducer(state:any,action:any) {
//     switch(action.type){
//         case INCREMENT:
//             return {number: state.number+1}
//         case DECREMENT:
//             return {number: state.number-1}
//         default:
//             return state;
//     }
// }

/** useState就是基于useReducer实现的*/

//自定义hooks
function useState(initialState: any){
  const reducer = useCallback((state, action/*dispatch的是action,dispatch(action),会传给这里*/) => action,[]);
  const [state, dispatch] = useReducer(reducer, initialState);
  function setState(payload: any){
    dispatch(payload/*dispatch的是action*/)
  }
  return [state, setState]
}

export default function App(){
  // let [state,dispatch] = useReducer(reducer,initialState)
  const [state,setState] = useState(initialState)

  return (
    <div>
      <p>{state.number}</p>
      <button onClick={()=>setState({number:state.number+1})}>+</button>
      <button onClick={()=>setState({number:state.number-1})}>-</button>
    </div>
  );

}
